openerp.one2many_search = function(instance) {
    instance.web.form.one2ManySearchBar = instance.web.form.FieldOne2Many.extend({
        multi_selection: true,
        init: function(field_manager, node) {
            this.search_bar_flag = true;
            this._super(field_manager, node);
        },
    });

    instance.web.form.One2ManyListViewSearchBar = instance.web.form.One2ManyListView.extend({
        _template: 'One2Many.listviewSearchBar',
        start: function() {
            this.vals = [];
            var ret = this._super.apply(this, arguments),
                self = this;


            self.on('list_view_loaded', self, function() {
                self.render_buttons();
            })

            this.$el.on('keydown', '.zzx_search_bar > input', function(e) {
                switch (e.which) {
                    case $.ui.keyCode.ENTER:
                        var val = $(this).val();
                        if (val) {
                            self.vals.push(val);
                            self.do_search_by_bar();
                        }
                        break;
                    case $.ui.keyCode.BACKSPACE:
                        if (self.vals.length > 0) {
                            self.vals.pop();
                            self.do_search_by_bar();
                        }
                        break;
                }
            }).on('click', '.zzx_search_bar .delete', function() {
                var text = $(this).parent().text();

                self.vals.remove(text.slice(0, text.length - 1));
                self.do_search_by_bar();
            }).on('click', '.zzx_buttons button', function() {
                var ids = [];
                self.$el.find('th.oe_list_record_selector input:checked')
                        .closest('tr').each(function () {
                    ids.push($(this).data('id'));
                });

                new instance.web.Model(self.model).call_button($(this).data('action'), [ids]).then(function() {
                    return self.do_search_by_bar();
                })
            })

            return ret;
        },

        do_select: function (ids, records, deselected) {
            var ret = this._super.apply(this, arguments);

            if (ids && ids.length > 0) {
                this.show_buttons();
            } else {
                this.hide_buttons();
            }

            return ret;
        },

        show_buttons: function () {
            $('.zzx_buttons').addClass('show');
        },

        hide_buttons: function () {
            $('.zzx_buttons').removeClass('show');
        },

        render_buttons: function() {
            $('.zzx_buttons > button').remove();
            var buttons = $('.zzx_buttons');

            if (this.ViewManager.o2m.options.buttons && this.ViewManager.o2m.options.buttons.length > 0) {
                var template = function(action, string) {
                    return '<button data-action="' + action + '">' + string + '</button>'
                }

                var innerHTML = '';
                this.ViewManager.o2m.options.buttons.forEach(function(button) {
                    innerHTML += template(button.action, button.string);
                });

                buttons.html(innerHTML);
            }
        },

        do_search_by_bar: function () {
            var self = this,
                options = self.o2m.options,
                controller = self.ViewManager.views[self.ViewManager.active_view].controller,
                domains = [];

            if (!options || !options.search_filter) {
                throw new Error('需要在 options 中添加 search_filter 字段')
            }

            self.vals.forEach(function(val) {
                var domain = [];
                options.search_filter.split(' ').forEach(function(filter) {
                    domain.push([filter, 'ilike', val])
                });

                var ors = [],
                    length = domain.length;

                for (var i = 0; i < length - 1; i++) {
                    domain.unshift('|');
                }

                domains = domains.concat(domain)
            })

            instance.web.pyeval.eval_domains_and_contexts({
                domains: [domains],
                contexts: [{}],
                group_by_seq: []
            }).done(function (results) {
                if (results.error) {
                    throw new Error('错误的domain条件');
                }

                $.when(controller.do_search(results.domain, results.context, [])).then(function() {
                    self.render_search_bar();
                })
            })
        },

        render_search_bar: function() {
            $('.zzx_search_bar > .tags').remove();
            var bar = $('.zzx_search_bar');

            if (this.vals.length > 0) {
                var template = function (val) {
                    return '<span class="tag">' + val + '<span class="delete">+</span></span>'
                }

                var innerHTML = '';
                this.vals.forEach(function(val) {
                    innerHTML += template(val);
                });

                bar.append($('<div class="tags">' + innerHTML + '</div>'))
            }

            bar.find('input').css('paddingLeft', (bar.find('.tags').width() || 4) + 'px').focus();
        }
    });

    instance.web.form.One2ManyViewManager.include({
        init: function(parent, dataset, views, flags) {
            this._super(parent, dataset, views, flags);

            if (parent && parent.search_bar_flag) {
                this.registry = this.registry.extend({
                    list: 'instance.web.form.One2ManyListViewSearchBar',
                });
            }
        },

    });

    instance.web.form.widgets = instance.web.form.widgets.extend({
        'one2many_search_bar' : 'instance.web.form.one2ManySearchBar',
    });
}
